﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HYBYSoft.Company.Models;
using HYBYSoft.Company.WebSite.Helper;
using System.Text;

namespace HYBYSoft.Company.WebSite.Filter
{
    public class EventLogFilterAttribute : FilterAttribute, IActionFilter
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        CompanySiteEntities _dbContext = new CompanySiteEntities();

        #region IActionFilter 成员
        /// <summary>
        /// Action请求后处理
        /// </summary>
        /// <param name="filterContext">筛选器上下文</param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }

        /// <summary>
        /// Action请求时处理
        /// </summary>
        /// <param name="filterContext">筛选器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //获得Cookie中的令牌信息
            HttpCookie token = filterContext.RequestContext.HttpContext.Request.Cookies[ConstDefinition.TOKEN_NAME];

            string currentUser = "匿名用户";
            if (token != null)
            {
                //对令牌信息进行拆分处理
                byte[] tokenByteArray = Convert.FromBase64String(token.Value);
                currentUser = (Encoding.UTF8.GetString(tokenByteArray)).Split('$')[1];
            }

            //创建日志信息
            EventLog log = new EventLog
            {
                EventMessage = string.Format("访问{0}控制器中的{1}方法", filterContext.RouteData.Values["controller"].ToString(), filterContext.RouteData.Values["action"].ToString()),
                EventDescription = string.Format("用户{0}于{1}{2}访问{3}控制器中的{4}方法", currentUser, DateTime.Now.ToLongDateString(),
                                    DateTime.Now.ToShortTimeString(), filterContext.Controller, filterContext.ActionDescriptor.ActionName),
                EventMachine = filterContext.HttpContext.Request.UserHostAddress,
                EventCategory = string.Format("Action:{0};HttpMethod:{1}", filterContext.ActionDescriptor.ActionName, filterContext.HttpContext.Request.HttpMethod),
                EventOperator = currentUser,                
                EventPriority = filterContext.HttpContext.Request.HttpMethod.ToLower() == "post" ? 2 : 1,
                ControllorName = filterContext.RouteData.Values["controller"].ToString(),
                ActionName = filterContext.RouteData.Values["action"].ToString(),
                EventTime = DateTime.Now,
            };

            _dbContext.AddToEventLogs(log);
            _dbContext.SaveChanges();
        }

        #endregion
    }
}